<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>

          <a-col :span="24">
            <a-form-model-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model.trim="model.name" placeholder="请输入联系人"  ></a-input>
<!--              <lianxiren v-model="model.contactsIds" :query-config="lianxirenConfig" :url="lianxirenUrl" v-if="model.customerId"></lianxiren>-->
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="联系电话" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="telephonesFalse">
              <a-button class="editable-add-btn" @click="telAdd">
                新增
              </a-button>
              <a-table
                bordered
                :dataSource="dataSource"
                :columns="columns"
                :pagination="false"
                rowKey="id"
              >
                <template slot="type" slot-scope="text, record">
                  <span>
                    <j-dict-select-tag type="list" v-model="text" dictCode="telephone_type" disabled />
                  </span>
                  <!--                  <editable-cell
                                      :ref="`phone_${record.key}`"
                                      decoratorType="integer"
                                      formType="input"
                                      :decoratorOptions="rules.phone"
                                      :defaultEditable="true"
                                      :required="true"
                                      :value="text"
                                      :text="text"
                                      placeholder="请输入手机号"
                                      :autoSave="true"
                                      @truefalseChange="truefalseChange"
                                      @valueChange="onInputChange(record.key, 'phone', $event)"
                                    />-->
                </template>

                <template slot="phone" slot-scope="text, record">
                  <span>{{ text }}</span>
                  <!--                  <editable-cell
                                      :ref="`type_${record.key}`"
                                      :decoratorOptions="rules.type"
                                      :text="record.type"
                                      :autoSave="true"
                                      :defaultEditable="true"
                                      :required="true"
                                      :value="text"
                                      formType="selectTag"
                                      dictCode="telephone_type "
                                      @selectTagChange="onCellChange(record.key, 'type',$event)"
                                    />-->
                </template>
                <span slot="operation" slot-scope="text, record,index">
                    <a @click="huikuandanTableEdit(record)">编辑</a>
                    <a-divider type="vertical" />
                    <a @click="huikuandanTableDel(index)">删除</a>
                  </span>
                <!--               <template slot="operation" slot-scope="text, record">
                      <a-popconfirm v-if="dataSource.length " title="确定要删除?" @confirm="() => batchDel(record)">
                             <span>
                               <a href="javascript:;">删除</a>
                             </span>
                                 </a-popconfirm>

                </template>-->
              </a-table>
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="24">-->
<!--            <a-form-model-item label="电话" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="telephones">-->
<!--              <a-button class="editable-add-btn" @click="telAdd">-->
<!--                新增-->
<!--              </a-button>-->
<!--&lt;!&ndash;              <a-button class="editable-add-btn" @click="saveTEL" type="primary" >-->
<!--                保存-->
<!--              </a-button>&ndash;&gt;-->
<!--              <a-table-->
<!--                bordered-->
<!--                :dataSource="dataSource"-->
<!--                :columns="columns"-->
<!--                :pagination="false"-->
<!--              >-->
<!--                <template slot="phone" slot-scope="text, record">-->
<!--                  <editable-cell-->
<!--                    :ref="`tel_${record.key}`"-->
<!--                    decoratorType="integer"-->
<!--                    formType="input"-->
<!--                    :decoratorOptions="rules.phone"-->
<!--                    :defaultEditable="true"-->
<!--                    :required="true"-->
<!--                    :value="text"-->
<!--                    :text="text"-->
<!--                    placeholder="请输入手机号"-->
<!--                    :autoSave="true"-->
<!--                    @valueChange="onInputChange(record.key, 'phone', $event)"-->
<!--                  />-->
<!--                </template>-->

<!--                <template slot="type" slot-scope="text, record">-->
<!--                  <editable-cell-->
<!--                    :ref="`region_${record.key}`"-->
<!--                    :decoratorOptions="rules.type"-->
<!--                    :text="record.type"-->
<!--                    :autoSave="true"-->
<!--                    :defaultEditable="true"-->
<!--                    :required="true"-->
<!--                    :value="text"-->
<!--                    formType="selectTag"-->
<!--                    dictCode="telephone_type "-->
<!--                    @selectTagChange="onCellChange(record.key, 'type',$event)"-->
<!--                  />-->
<!--                </template>-->
<!--                <template slot="operation" slot-scope="text, record" >-->
<!--                  <a-popconfirm v-if="dataSource.length " title="确定要删除?" @confirm="() => batchDel(record)">-->
<!--              <span>-->
<!--                <a href="javascript:;">删除</a>-->

<!--              </span>-->
<!--                  </a-popconfirm>-->

<!--                </template>-->
<!--              </a-table>-->
<!--            </a-form-model-item>-->

<!--          </a-col>-->
          <a-col :span="24">
            <a-form-model-item label="关联客户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId">
              <!--              <j-search-select-tag v-model="model.customerId" dict="biz_customer,name,id"  />-->
              <JSelectMultiUser v-model="model.customerId" :query-config="selectUserQueryConfig" :url="kehuurl"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="email">
              <a-input v-model="model.email" placeholder="请输入邮箱"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="QQ" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="qq">
              <a-input v-model="model.qq" placeholder="请输入QQ"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="address">
              <j-area-linkage type="cascader" v-model="model.address" placeholder="请选择省市区"  />
            </a-form-model-item>
          </a-col>
          <!--          <a-col :span="24">-->
          <!--            <a-form-model-item label="地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="address">-->
          <!--              <a-input v-model="model.address" placeholder="请输入地址"  ></a-input>-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <a-col :span="24">
            <a-form-model-item label="地址详情" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="addressInfo">
              <a-input v-model="model.addressInfo" placeholder="请输入地址详情"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="邮编" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="postalCode">
              <a-input v-model="model.postalCode" placeholder="请输入邮编"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="gender">
              <j-dict-select-tag type="list" v-model="model.gender" dictCode="Gender" placeholder="请选择性别" />
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="24">-->
<!--            <a-form-model-item label="生日" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="birthday">-->
<!--              <a-input v-model="model.birthday" placeholder="请输入生日"  ></a-input>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
          <a-col :span="24">
            <a-form-model-item label="生日" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="birthday">
              <j-date placeholder="请选择生日" v-model="model.birthday" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="爱好" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="hobby">
              <a-input v-model="model.hobby" placeholder="请输入爱好"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-input v-model="model.remark" placeholder="请输入备注"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="department">
              <a-input v-model="model.department" placeholder="请输入部门"  ></a-input>
            </a-form-model-item>
<!--            <a-form-model-item label="部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="department">-->
<!--              <j-select-depart v-model="model.department" :multi="true"  />-->
<!--            </a-form-model-item>-->
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="职务" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="post">
              <a-input v-model="model.post" placeholder="请输入职务"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="级别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="level">
              <j-dict-select-tag type="list" v-model="model.level" dictCode="constacts_level" placeholder="请选择级别" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="directorIds">

              <j-select-user-by-dep v-model="model.directorIds" :multi="true" />
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="协同人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="collaboratorIds">

              <j-select-user-by-dep v-model="model.collaboratorIds" :multi="true" />
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="24">-->
<!--            <a-form-model-item label="重要程度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="importance">-->
<!--              <a-input-number v-model="model.importance" placeholder="请输入重要程度(1-5)" style="width: 100%" />-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--          <a-col :span="24">-->
<!--            <a-form-model-item label="重要程度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="importance">-->
<!--              <a-rate :defaultValue="3" v-model="importance" @change="arateChange" />-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
          <a-col :span="24">
            <a-form-model-item label="重要程度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="importance">
              <a-rate v-model="importance" @change="arateChange" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="决策关系" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="relationBetween">
              <j-dict-select-tag type="list" v-model="model.relationBetween" dictCode="consacts_relation" placeholder="请选择决策关系" />
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="24">-->
<!--            <a-form-model-item label="亲密度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="intimacy">-->
<!--              <a-input v-model="model.intimacy" placeholder="请输入亲密度（0-5）"  ></a-input>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
          <a-col :span="24">
            <a-form-model-item label="亲密度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="intimacy">
              <a-rate :defaultValue="3" v-model="intimacy" @change="arate2Change" />
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="24">-->
<!--            <a-form-model-item label="创建时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">-->
<!--              <j-date placeholder="请选择创建时间"  v-model="model.createTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
        </a-row>
      </a-form-model>
    </j-form-container>
    <TELModal ref="TELModal" @ok="TELOK"></TELModal>
  </a-spin>

</template>

<script>
import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDepCustom'
/* import JSelectUserByDepModalCustom from '@/components/jeecgbiz/modal/JSelectUserByDepModalCustom' */
  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import EditableCell from '@/components/EditableCell/cell'
  import { checkOnlyUser } from '@api/api'
  import JSelectMultiUser from '@/components/jeecgbiz/JSelectMultiUserCustom'
  import lianxiren from '@/components/jeecgbiz/lianxirenCustom'
import TELModal from '@views/customer/modules/TELModal'


  export default {
    name: 'ContactsForm',
    components: {
      EditableCell,
      JSelectMultiUser,
      lianxiren,
      // JSelectUserByDepModalCustom,
      JSelectUserByDep,
      TELModal

    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    watch:{
      dataSource: {
        deep: true,
        immediate: true,
        handler(newValue, oldValue) {
          this.model.telephones = newValue
          if (newValue.length > 0) {
            this.model.telephonesFalse = JSON.stringify(newValue)
          } else {
            this.model.telephonesFalse = ''
          }

          console.log('电话数组', this.model)
        }
      },
      'model.customerId':{
        deep:true,
        handler(newValue, oldValue){
          this.lianxirenUrl='/sys/common/queryCustomerId?customerId='+newValue
          if(!newValue){
            this.model.contactsIds=''
          }
        }
      }
    },
    data () {
      return {
        importance:0,
        intimacy:0,
        kehuurl:'/customer/customer/lists?filed=2',
        // 选择用户查询条件配置
        selectUserQueryConfig: [
          {key: 'phone', label: '电话'},
        ],
        //联系人
        lianxirenUrl:'/sys/common/queryCustomerId?customerId=',
        lianxirenConfig: [
          {key: 'phone', label: '电话'},
        ],
        //电话表格使用=====开始
        dataSource: [],
        loading: false,
        count: 1,
        columns: [
          {
            title: '类型',//1.工作 2.手机 3.住址 4.主要 5.传真 6.其他
            dataIndex: 'type',
            width:'30%',
            scopedSlots: { customRender: 'type' },
          },
          {
            title: '电话',
            dataIndex: 'phone',
            width:'40%',
            scopedSlots: { customRender: 'phone' },
          },

          {
            title: '操作',
            dataIndex: 'operation',
            width:'30%',
            scopedSlots: { customRender: 'operation' },
          },
        ],
        //电话表格使用=====结束

        model:{
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          customerId: [
            { required: true, message: '请选择客户名称!'},
          ],
          name: [
            { required: true, message: '请输入联系人!'},
          ],
          directorIds:[
            { required: true, message: '请选择负责人!'},
          ],
          telephonesFalse: [
            { required: true, message: '请输入电话!'},
            {
              validator: (rule, value, callback) =>{
                console.log('telephones',value)
                for (let dataSourceElement of this.dataSource) {
                  if(dataSourceElement.phone=='' || dataSourceElement.type==''){
                    callback(false)
                  }
                }
                callback()
              },
              message: '请填写完整',
              trigger: ['change']
            }
          ],
          email: [
            { required: false},
            { pattern: /^([\w]+\.*)([\w]+)@[\w]+\.\w{3}(\.\w{2}|)$/, message: '请输入正确的电子邮件!'},
          ],
          qq: [
            { required: false},
            { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},
          ],
          postalCode: [
            { required: false},
            { pattern: /^[1-9]\d{5}$/, message: '请输入正确的邮政编码!'},
          ],
        },
        fields: [
          'phone',
          'type'
        ],
        rules:{
          type: {
            rules: [
              {
                required: true,
                message: '请选择类型',
              },
            ],
          },

          phone:{
            rules: [
              {
                required: true,
                message: '请输入手机号',
              },
              {
                validator: (rule, value, callback) =>{
                  let valuetrim = value.trim()
                  if(!valuetrim){
                    callback(new Error("不能为空"))
                  }else{
                    callback()

                  }



                },
                message: '不能为空',
                trigger: ['blur']
              }
              // {
              //   validator: (rule, value, callback) =>{
              //     var reg=/^1[3456789]\d{9}$/
              //     if(!reg.test(value)){
              //       callback(new Error("请输入正确手机号"))
              //     }else{
              //       callback()
              //
              //     }
              //
              //
              //
              //   },
              //   message: '请输入正确手机号',
              //   trigger: ['change']
              // }
            ],
          }
        },
        url: {
          add: "/contacts/contacts/add",
          edit: "/contacts/contacts/edit",
          queryById: "/contacts/contacts/queryById"
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
      //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      arateChange(e) {
        console.log(e)
        this.model.importance = e
      },
      arate2Change(e) {
        console.log(e)
        this.model.intimacy = e
      },
      //类型转换
      NumberChange(e) {
        return Number(e)
      },
      telAdd() {
        /* const { count, dataSource } = this
        const newData = {
          key: count,
          phone: '',
          type: ''
        }
        this.dataSource = [...this.dataSource, newData]
        this.count += 1 */
        this.$refs.TELModal.title = '新增联系方式'
        this.$refs.TELModal.disableSubmit = false
        this.$nextTick(() => {
          this.$refs.TELModal.passON(this.model.telephones)
        })

        this.$refs.TELModal.add()
      }
      ,


      // telAdd(){
      //   const { count, dataSource } = this
      //   const newData = {
      //     key: count,
      //     phone:'',
      //     type:''
      //   }
      //   this.dataSource = [...this.dataSource, newData]
      //   // this.dataSource.push(newData)
      //   this.count += 1
      // },
      TELOK(res) {
        console.log('add应收款返回数据', res)
        const { count, dataSource } = this
        if (res.key) {
          //编辑的情况
          const dataSource = [...this.dataSource]
          let target = dataSource.find((item) => item.key == res.key)
          target = Object.assign(target, res)
          this.dataSource = dataSource
        } else {
          //新增的情况
          let newData = Object.assign(res, { key: count })
          this.dataSource = [...this.dataSource, newData]
          this.count += 1
        }

        //这里要区分是编辑还是新增的回传

        console.log('客户电话表格实时动态', this.dataSource)
      },
      saveTEL() {
        const newData = [...this.dataSource]
        this.model.telephones = newData
        console.log('111111111111111111111', this.model.telephones)
      }
      ,
      // saveTEL(){
      //   console.log(this.dataSource)
      //   // debugger
      //   const newData = [...this.dataSource]
      //   this.model.telephones = newData


      // },
      batchDel(record) {
        console.log('删除行',record)
        // 新增时用KEY 删除时候用ID 删除的时候没有key
        this.onDelete(record.key||record.id)
      },
      // 删除
      onDelete(key) {
        console.log('key',key)
        // 拷贝数组数据
        const dataSource = [...this.dataSource]
        // 过滤移除当前项目  新增时用KEY 删除时候用ID 删除的时候没有key
        this.dataSource = dataSource.filter((item) => (item.key?item.key:item.id) !== key)
      },
      onInputChange(key, dataIndex, value) {
        const dataSource = [...this.dataSource]
        const target = dataSource.find((item) => item.key === key)
        if (target) {
          target[dataIndex] = value == '' ? undefined : value
          this.dataSource = dataSource
        }
      },
      onCellChange(key, dataIndex, value) {
        // console.log(value)
        // console.log(dataIndex)
        const dataSource = [...this.dataSource]
        const target = dataSource.find((item) => item.key === key)
        console.log(target)

        if (target && value==0) {
          target[dataIndex] = value
          // dataSource[dataIndex].endDate = ''
          // dataSource[dataIndex].startDate = ''
          this.dataSource = dataSource.map((item) => {
            if(item.key === key){
              return item
            }else {
              return item
            }
          } )
        }else {
          target[dataIndex] = value
          this.dataSource = dataSource
        }
      },
      // validateRow可以提取为公共函数
      validateRow(key, fields, callback) {
        // 查找验证是否通过
        const row = {}
        let err = false
        // forEach 对每一个验证，可以更改为some满足一个就提醒
        fields.forEach((filed) => {
          let refName = `${filed}_${key}`
          let result = this.$refs[refName].validate()
          row[filed] = result.value
          if (!result.success) {
            err = true
          }
        })
        callback(err, row)
      },
      add () {
        this.edit(this.modelDefault);
        // this.model.importance = 3
        // this.model.intimacy = 3
        this.isShow = false
      },
      // 获取电话信息
      getTelInfo(){
        getAction(this.url.queryById,{id:this.model.id}).then(res=>{
          console.log("获取电话信息",res)
          this.dataSource = res.result.telephones
        })

      },
      edit (record) {
        this.model = Object.assign({}, record);
        if(this.model.importance){
          this.importance = Number(this.model.importance)
        }
        if(this.model.intimacy){
          this.intimacy = Number(this.model.intimacy)
        }
        if (this.model.telephones) {
          this.dataSource = this.model.telephones
        }
        console.log("编辑数据",this.model)
        this.getTelInfo()
        this.visible = true;
        console.log(typeof this.model.telephones)

        // this.model.telephoneIds = []
        // this.dataSource = this.model.telephones
      },
      //回款单表格编辑
      huikuandanTableEdit(record) {
        console.log('record', record)
        let guolv = this.dataSource.filter(res => {
          return res.phone !== record.phone
        })
        console.log('除了本条，其他过滤出来的', guolv)
        this.$refs.TELModal.title = '编辑客户联系方式'
        this.$refs.TELModal.disableSubmit = false
        this.$refs.TELModal.edit(record)
        this.$refs.TELModal.passONEdit(guolv)
      },
      //回款单表格删除
      huikuandanTableDel(index) {
        console.log('index', index)
        this.dataSource.splice(index, 1)
        if (this.dataSource.length <= 0) {
          this.model.telephonesFalse = ''
        }
      },
      submitForm () {
        console.log('this.model',this.model)
        if (!this.model.importance) {
          this.model.importance = 0
        }
        if (!this.model.intimacy) {
          this.model.intimacy = 0
        }
        // this.model.importance = this.NumberChange(this.model.importance)
        // console.log('提交this.model.importance', typeof this.model.importance)
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
              method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
    },


  }
</script>
<style>
.editable-cell {
  position: relative;
}

.editable-cell-input-wrapper,
.editable-cell-text-wrapper {
  padding-right: 24px;
}

.editable-cell-text-wrapper {
  padding: 5px 24px 5px 5px;
}

.editable-cell-icon,
.editable-cell-icon-check {
  position: absolute;
  right: 0;
  width: 20px;
  cursor: pointer;
}

.editable-cell-icon {
  line-height: 18px;
  display: none;
}

.editable-cell-icon-check {
  line-height: 28px;
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}

.editable-cell-icon:hover,
.editable-cell-icon-check:hover {
  color: #108ee9;
}

.editable-add-btn {
  margin-bottom: 8px;
  margin-right: 10px;
}
</style>